package com.qdlc.p2p.dal.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.TppDao;
import com.qdlc.p2p.dal.dto.Tpp;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.SystemConfigs;

/**
 * 第三方请求记录操作dao
 * @author wjx
 * @version 2.0
 * @date 2015年6月5日 下午6:00:56
 */
@Repository("tppDao")
public class TppDaoImpl extends BaseDaoImpl<Tpp> implements TppDao {

	private Logger logger = Logger.getLogger(TppDaoImpl.class);
	
	@SuppressWarnings("rawtypes")
	@Override
	public Tpp getTppByOrdId(String ordId) {
		String jpql = "from Tpp where orderId =?1";
		Query query = em.createQuery(jpql);
		query.setParameter(1, ordId);
		List list = query.getResultList();
		if (null !=list && list.size()>0) {
			return (Tpp)list.get(0);
			
		}
		return null;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public Tpp getTppByCustId(TppModel model) {
		String jpql = "from Tpp where "+"(tppUserCustId =?1 or toTppUserCustId =?2)"+" and status !=?3 ";
		Query query = em.createQuery(jpql);
		query.setParameter(1, model.getTppUserCustId());
		query.setParameter(2, model.getToTppUserCustId());
		query.setParameter(3, model.getStatus());
		List list = query.getResultList();
		if (null !=list && list.size()>0) {
			return (Tpp)list.get(0);
			
		}
		return null;
	}

    @Override
    public Tpp getTppByCustId(String tppUserCustId,String toTppUserCustId,int status) {
        String jpql = "from Tpp where "+"(tppUserCustId =?1 or toTppUserCustId =?2)"+" and status !=?3 ";
        Query query = em.createQuery(jpql);
        query.setParameter(1, tppUserCustId);
        query.setParameter(2, toTppUserCustId);
        query.setParameter(3, status);
        List list = query.getResultList();
        if (null !=list && list.size()>0) {
            return (Tpp)list.get(0);

        }
        return null;
    }

	@Override
	public Tpp getTppBySubOrdId(String subOrdId) {
		String jpql = "from Tpp where subOrdId =?1";
		Query query = em.createQuery(jpql);
		query.setParameter(1, subOrdId);
		List list = query.getResultList();
		if (null !=list && list.size()>0) {
			return (Tpp)list.get(0);
		}
		return null;
	}

	@Override
	public PageDataList<TppModel> findRefundList(AccountModel model) {
		QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
		param.addOrder(OrderFilter.OrderType.DESC, "addTime");
		if (StringUtil.isNotBlank(model.getSearchName())) {
			param.addParam("subOrdId", model.getSearchName());
		}
		param.addParam("tppType", "refund");
		PageDataList<Tpp> dataList = this.findPageList(param);
		PageDataList<TppModel> dataList_ = new PageDataList<TppModel>();
		List<TppModel> list = new ArrayList<TppModel>();
		if (null != dataList.getList() && dataList.getList().size() > 0) {
			for (Tpp tpp : dataList.getList()) {
				TppModel tppModel = TppModel.instance(tpp);
				if (StringUtil.isBlank(tppModel.getToTppUserCustId()))
					tppModel.setToTppUserCustId("平台");
				list.add(tppModel);
			}
		}
		dataList_.setPage(dataList.getPage());
		dataList_.setList(list);
		return dataList_;
	}

	@Override
	public PageDataList<TppModel> pageDataList(TppModel model) {
		QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
		if (StringUtil.isNotBlank(model.getSearchName())) {
			param.addParam("toUser.userName", model.getSearchName());
		} else {
			if (StringUtil.isNotBlank(model.getUserName())) {
				param.addParam("user.userName", model.getUserName());
			}
			if (StringUtil.isNotBlank(model.getToUserName())) {
				param.addParam("toUser.userName", model.getToUserName());
			}
			if (StringUtil.isNotBlank(model.getToUserMobile())) {
				param.addParam("toUser.mobilePhone", model.getToUserMobile());
			}
			if (StringUtil.isNotBlank(model.getToUserRealName())) {
				param.addParam("toUser.realName", model.getToUserRealName());
			}
			if (model.getStatus() != 99) {
				param.addParam("status", model.getStatus());
			}
			if (StringUtil.isNotBlank(model.getTppType())) {
				param.addParam("tppType", model.getTppType());
			}
			if (StringUtil.isNotBlank(model.getServiceType())) {
				param.addParam("serviceType", model.getServiceType());
			}
			if (StringUtil.isNotBlank(model.getOrderId())) {
				param.addParam("orderId", model.getOrderId());
			}
			if (StringUtil.isNotBlank(model.getUuid())) {
				param.addParam("borrow.uuid", model.getUuid());
			}
			if (StringUtil.isNotBlank(model.getStartTime())) {
				Date start = DateUtil.valueOf(model.getStartTime() + " 00:00:00");
				param.addParam("addTime", Operators.GTE, start);
			}
			if (StringUtil.isNotBlank(model.getEndTime())) {
				Date end = DateUtil.valueOf(model.getEndTime() + " 23:59:59");
				param.addParam("addTime", Operators.LTE, end);
			}
		}
		
		PageDataList<Tpp> dataList = this.findPageList(param);
		PageDataList<TppModel> dataList_ = new PageDataList<TppModel>();
		List<TppModel> list = new ArrayList<TppModel>();
		
		if(dataList.getList() != null && dataList.getList().size() > 0) {
			String tppName = SystemConfigHelper.getValue(Nid.TPP_NAME);
			String webName = SystemConfigs.WEB_NAME;
			for (Tpp tpp : dataList.getList()) {
				TppModel tppModel = TppModel.instance(tpp);
				if (tpp.getUser() != null) {
					if (("repay".equals(tpp.getTppType()) || "red_envelope_exchange".equals(tpp.getTppType())) && (tpp.getRespDesc() != null && tpp.getRespDesc().contains("代付"))) {
						tppModel.setUserName(tppName);
					} else {
						tppModel.setUserName(tpp.getUser().getUserName());
					}
				} else if (tpp.getUser() == null && "red_envelope_exchange".equals(tpp.getTppType()) && (tpp.getRespDesc() != null && tpp.getRespDesc().contains("代付"))){
					tppModel.setUserName(tppName);
				} else {
					tppModel.setUserName(webName);
				}
				if (tpp.getToUser() != null) {
					if (("repay".equals(tpp.getTppType()) || "red_envelope_exchange".equals(tpp.getTppType())) && (tpp.getRespDesc() != null && tpp.getRespDesc().contains("代收"))) {
						tppModel.setToUserName(tppName);
						tppModel.setToUserRealName(tppName);
					} else {
						tppModel.setToUserName(tpp.getToUser().getUserName());
						tppModel.setToUserRealName(tpp.getToUser().getRealName());
						tppModel.setToUserMobile(tpp.getToUser().getMobilePhone());
					}
				} else {
					tppModel.setToUserName(webName);
					tppModel.setToUserRealName(webName);
				}
				list.add(tppModel);
			}
		}
		dataList_.setList(list);
		dataList_.setPage(dataList.getPage());
		return dataList_;
	}
	
	@Override
    public void updateStatus(long id, int status) {
        String sql = "UPDATE Tpp SET status = :status WHERE id = :id AND status != :status";
        Query query = em.createQuery(sql);
        query.setParameter("status", status);
        query.setParameter("id", id);
        int result = query.executeUpdate();
        if (result != 1) {
            logger.error("执行调度任务，更改调度状态失败！---------------- ID:" + id + ",result:" + result + ",status:" + status);
            throw new BusinessException("执行调度任务，更改调度状态失败！", 1);
        }
        refresh(super.find(id));
    }

}
